package com.kang.mavenweb.dao;

import com.kang.mavenweb.domain.User;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Repository
public class LoginDaoImpl extends HibernateDaoSupport implements ILoginDao {

    @Autowired
    public void setSuperSessionFactory(SessionFactory superSessionFactory){
        super.setSessionFactory (superSessionFactory);
    }

    @Transactional
    @Override
    public List<User> login(User user) {
        String username = user.getUsername ( );
        String password = user.getPassword ( );
        Session currentSession = this.getSessionFactory ( ).getCurrentSession ( );
        Query from_t_user = currentSession.createQuery ("from User u where u.username=? and u.password=?");
        from_t_user.setParameter (0, username);
        from_t_user.setParameter (1, password);
        return from_t_user.list ();
    }

    @Transactional
    @Override
    public void add(User user) {
        this.getHibernateTemplate ( ).save (user);
    }

   @Transactional
    @Override
    public List<User> findById(int id) {
        Session currentSession = this.getSessionFactory ( ).getCurrentSession ( );
        Query from_t_user = currentSession.createQuery ("from User u where u.id=?");
        from_t_user.setParameter (0, id);
        return from_t_user.list ();
    }
}
